package com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类 使用Durid连接池
 */
public class JdbcUtils {
    private static DataSource ds;

    //静态代码块，当类被加载的时候执行
    static {
        Properties pro = new Properties();
        try {
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接Connection对象
     */
    public static Connection getCon() {
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throw new RuntimeException("获取数据库连接失败", throwables);
        }
    }

    /* @SuppressWarnings("finally")
    public static Connection getCon() {
        Connection con = null;
        //驱动程序名
        String driver = "com.mysql.jdbc.Driver";

        //URL指定要访问的数据库名
//			String url="jdbc:mysql://localhost/ruangong?user=root&password=727112&useUnicode=true&characterEncoding=GB2312";
        String url = "jdbc:mysql://47.116.68.226/ruangong?user=root&password=123456&useSSL=false&serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8";

        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url);
        } catch (ClassNotFoundException e) {
            System.out.println("Sorry,can't find the Driver!");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Error!");
            e.printStackTrace();
        } finally {
            return con;
        }
    } */

    public static void close2(Connection con, Statement stat) {
        try {
            if (stat != null) {
                stat.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close3(ResultSet rs, Connection con, Statement stat) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stat != null) {
                stat.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*
    public static void close3p(ResultSet rs, Connection con, PreparedStatement pstat) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            pstat.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    } */

}
		
			

